<?php
namespace Admin\Cli\Tasks;

use Helpers\Main;
use Helpers\Queue;
use Helpers\Tool;
use Helpers\XhException;
use Phalcon\Cli\Task;
use Phalcon\Queue\Beanstalk;
use Phalcon\Logger\Adapter\File;

class QueueTask extends Task
{

    private function _log($action, $content, $msg = '执行成功', $description = [])
    {
        Main::createCommitLog(
            'admin',
            'queue',
            $action,
            ['content' => $content, 'description' => $description],
            null,
            $msg
        );
    }

    /**
     * 队列消费
     *
     * create by ck 20180731
     */
    public function mainAction()
    {
        error_reporting(E_ALL);
        try {
            while ($job = Queue::reserve(1)) {
                $detail = $job->getBody();
                $action  = $detail['action'];
                $content = $detail['content'];

                if (method_exists($this, $action)) {
                    try {
                        $result = $this->$action($content);
                        $this->_log($action, $content, $result);
                    } catch (XhException $e) {
                        $this->_log($action, $content, $e->getMessage(), $e->getDescription());
                    } catch (\Exception $e) {
                        $this->_log($action, $content, $e->getMessage(), $e->getTrace());
                    }
                }
                else {
                    $this->_log($action, $content, '方法不存在');
                }
                $job->delete();
            }
        } catch (\Exception $e) {
            $this->_log('main', [], $e->getMessage(), $e->getTrace());
        }
    }

    private function testLog($content)
    {
        //执行
        $log = new File(Tool::buildPath(CACHE_PATH, 'logs/testLog.log'));
        $result = $log->info(json_encode($content));
        if (!$result) {
            throw new XhException('创建日志失败'); //失败抛出异常
        }
        return '创建日志成功'; //返回字符串则记录日志（默认"执行成功"）
    }

}
